package BackUpAction;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;
import com.zehon.exception.FileTransferException;

public class SCP {
	
	
	public static void sftpFile(File localFile, String username,
			String password, String hostname, String remoteDirectory)
			throws JSchException, SftpException, FileNotFoundException {
		System.out.println("Dang copy "+localFile.getAbsolutePath());
		JSch jsch = new JSch();
		String filename = localFile.getName();
		Session session = jsch.getSession(username, hostname, 22);
		session.setUserInfo(new HardcodedUserInfo(password));
		Properties config = new Properties();
		config.setProperty("StrictHostKeyChecking", "no");
		session.setConfig(config);
		session.connect();
		ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
		channel.connect();
		channel.cd(remoteDirectory);
		channel.put(new FileInputStream(localFile), filename);
		channel.disconnect();
		session.disconnect();
	}
	private static class HardcodedUserInfo implements UserInfo {

        private final String password;

        private HardcodedUserInfo(String password) {
            this.password = password;
        }

        public String getPassphrase() {
            return null;
        }

        public String getPassword() {
            return password;
        }

        public boolean promptPassword(String s) {
            return true;
        }

        public boolean promptPassphrase(String s) {
            return true;
        }

        public boolean promptYesNo(String s) {
            return true;
        }

        public void showMessage(String s) {
            System.out.println("message = " + s);
        }
    }

	public static void main(String[] args) throws FileTransferException, FileNotFoundException, JSchException, SftpException {
		String sourceFilePath = "/home/vinh/de8a2.mp3";
		String destFilePath = "/data/mcache/cache/music/musicdata42";
		sftpFile(new File(sourceFilePath), "vinh", "", "www.viplok.org", destFilePath);
	}
}